//导入express
const express = require("express");
//创建新的router
const router = express.Router();
const db = require("./mysql.js");
// //user注册的接口
router.post("/login", (req, res) => {
    var userInfo = req.body;//前端通过post，访问接口传过来的数据
    console.log(userInfo)
    const username = userInfo.user_name;
    const sqlstr = "SELECT * FROM shopping.user where user_name=?";
    db.query(sqlstr, username, (err, result) => {
        if (err) {
            return res.send({ status: "1", message: "登录失败" })
        }
        console.log(result);
        if (result.length > 0) {
            res.send({
                status: 1,
                message: "用户被占用"
            })
        }
        const sqlstr = `INSERT INTO shopping.user (user_name,password,nick_name) VALUES(?,?,?)`;
        db.query(sqlstr, [userInfo.user_name, userInfo.password, userInfo.nick_name], (err, result) => {
            if (err) {
                return res.send({ status: "1", message: err.message })
            }
            if (result.affectdRows === 1) {
                console.log("新增数据成功");
            }
        })
    })

})

//登录接口
router.post("/sign", (req, res) => {
    var userinfo = req.body;//前端通过post请求，访问接口传过来的数据
    const sqlstr = "select * from shopping.user where user_name=?"
    db.query(sqlstr, [userinfo. user_name], (err, results) => {
        if (err) return res.send({ status: "1", message: "登录失败" })
        if (results.length != 1) return res.send({ status: "1", message: "用户不存在" })
        if (results[0].password != userinfo.password) return res.send({ status: "1", message: "密码错误" })
        console.log("添加成功");
    })
})


module.exports = router;
